#!/bin/bash

# YQuote 实时行情订阅服务启动脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查依赖
check_dependencies() {
    print_info "检查系统依赖..."
    
    # 检查CMake
    if ! command -v cmake &> /dev/null; then
        print_error "CMake 未安装，请先安装 CMake 3.15+"
        exit 1
    fi
    
    # 检查Python
    if ! command -v python3 &> /dev/null; then
        print_error "Python3 未安装，请先安装 Python 3.8+"
        exit 1
    fi
    
    # 检查pip
    if ! command -v pip3 &> /dev/null; then
        print_error "pip3 未安装，请先安装 pip"
        exit 1
    fi
    
    print_success "依赖检查完成"
}

# 编译C++后端
build_cpp_backend() {
    print_info "编译C++后端..."
    
    cd cpp_backend
    
    # 创建构建目录
    if [ ! -d "build" ]; then
        mkdir build
    fi
    
    cd build
    
    # 配置和编译
    cmake .. || {
        print_error "CMake配置失败"
        exit 1
    }
    
    make -j$(nproc) || {
        print_error "编译失败"
        exit 1
    }
    
    cd ../..
    print_success "C++后端编译完成"
}

# 安装Python依赖
install_python_deps() {
    print_info "安装Python依赖..."
    
    cd python_api
    
    # 创建虚拟环境（可选）
    if [ "$1" = "--venv" ]; then
        if [ ! -d "venv" ]; then
            python3 -m venv venv
        fi
        source venv/bin/activate
    fi
    
    # 安装依赖
    pip3 install -r requirements.txt || {
        print_error "Python依赖安装失败"
        exit 1
    }
    
    cd ..
    print_success "Python依赖安装完成"
}

# 创建必要的目录
create_directories() {
    print_info "创建必要的目录..."
    
    mkdir -p logs
    mkdir -p cpp_backend/logs
    mkdir -p python_api/logs
    
    print_success "目录创建完成"
}

# 启动C++后端
start_cpp_backend() {
    print_info "启动C++后端服务..."
    
    cd cpp_backend/build
    
    # 检查可执行文件是否存在
    if [ ! -f "quote_server" ]; then
        print_error "quote_server 可执行文件不存在，请先编译"
        exit 1
    fi
    
    # 启动服务器
    ./quote_server &
    CPP_PID=$!
    
    cd ../..
    
    # 等待服务器启动
    sleep 2
    
    # 检查进程是否还在运行
    if kill -0 $CPP_PID 2>/dev/null; then
        print_success "C++后端服务已启动 (PID: $CPP_PID)"
        echo $CPP_PID > cpp_backend.pid
    else
        print_error "C++后端服务启动失败"
        exit 1
    fi
}

# 启动Python API
start_python_api() {
    print_info "启动Python API服务..."
    
    cd python_api
    
    # 激活虚拟环境（如果存在）
    if [ -d "venv" ]; then
        source venv/bin/activate
    fi
    
    # 启动API服务
    python3 app.py &
    PYTHON_PID=$!
    
    cd ..
    
    # 等待服务器启动
    sleep 3
    
    # 检查进程是否还在运行
    if kill -0 $PYTHON_PID 2>/dev/null; then
        print_success "Python API服务已启动 (PID: $PYTHON_PID)"
        echo $PYTHON_PID > python_api.pid
    else
        print_error "Python API服务启动失败"
        exit 1
    fi
}

# 停止服务
stop_services() {
    print_info "停止服务..."
    
    # 停止Python API
    if [ -f "python_api.pid" ]; then
        PYTHON_PID=$(cat python_api.pid)
        if kill -0 $PYTHON_PID 2>/dev/null; then
            kill $PYTHON_PID
            print_success "Python API服务已停止"
        fi
        rm -f python_api.pid
    fi
    
    # 停止C++后端
    if [ -f "cpp_backend.pid" ]; then
        CPP_PID=$(cat cpp_backend.pid)
        if kill -0 $CPP_PID 2>/dev/null; then
            kill $CPP_PID
            print_success "C++后端服务已停止"
        fi
        rm -f cpp_backend.pid
    fi
}

# 检查服务状态
check_status() {
    print_info "检查服务状态..."
    
    # 检查C++后端
    if [ -f "cpp_backend.pid" ]; then
        CPP_PID=$(cat cpp_backend.pid)
        if kill -0 $CPP_PID 2>/dev/null; then
            print_success "C++后端服务运行中 (PID: $CPP_PID)"
        else
            print_warning "C++后端服务未运行"
        fi
    else
        print_warning "C++后端服务未启动"
    fi
    
    # 检查Python API
    if [ -f "python_api.pid" ]; then
        PYTHON_PID=$(cat python_api.pid)
        if kill -0 $PYTHON_PID 2>/dev/null; then
            print_success "Python API服务运行中 (PID: $PYTHON_PID)"
        else
            print_warning "Python API服务未运行"
        fi
    else
        print_warning "Python API服务未启动"
    fi
    
    # 检查端口
    print_info "检查端口占用..."
    if netstat -tuln 2>/dev/null | grep -q ":8080 "; then
        print_success "端口 8080 (C++后端) 已监听"
    else
        print_warning "端口 8080 未监听"
    fi
    
    if netstat -tuln 2>/dev/null | grep -q ":8000 "; then
        print_success "端口 8000 (Python API) 已监听"
    else
        print_warning "端口 8000 未监听"
    fi
}

# 显示帮助信息
show_help() {
    echo "YQuote 实时行情订阅服务启动脚本"
    echo ""
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  build     - 编译C++后端"
    echo "  install   - 安装Python依赖"
    echo "  start     - 启动所有服务"
    echo "  stop      - 停止所有服务"
    echo "  restart   - 重启所有服务"
    echo "  status    - 检查服务状态"
    echo "  clean     - 清理构建文件"
    echo "  help      - 显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 build install start  # 完整构建和启动"
    echo "  $0 restart              # 重启服务"
    echo "  $0 status               # 检查状态"
}

# 清理构建文件
clean_build() {
    print_info "清理构建文件..."
    
    rm -rf cpp_backend/build
    rm -rf python_api/venv
    rm -rf python_api/__pycache__
    rm -rf python_api/**/__pycache__
    rm -f *.pid
    
    print_success "清理完成"
}

# 主函数
main() {
    echo "🚀 YQuote 实时行情订阅服务"
    echo "================================"
    
    case "$1" in
        "build")
            check_dependencies
            create_directories
            build_cpp_backend
            ;;
        "install")
            install_python_deps $2
            ;;
        "start")
            create_directories
            start_cpp_backend
            start_python_api
            echo ""
            print_success "所有服务已启动！"
            echo ""
            echo "🌐 访问地址:"
            echo "  - API文档: http://localhost:8000/docs"
            echo "  - 健康检查: http://localhost:8000/health"
            echo "  - WebSocket: ws://localhost:8000/ws"
            echo ""
            echo "📊 测试命令:"
            echo "  curl http://localhost:8000/api/quotes/"
            echo "  python3 tests/test_websocket_client.py"
            ;;
        "stop")
            stop_services
            ;;
        "restart")
            stop_services
            sleep 2
            start_cpp_backend
            start_python_api
            print_success "服务已重启"
            ;;
        "status")
            check_status
            ;;
        "clean")
            stop_services
            clean_build
            ;;
        "help"|"--help"|"-h")
            show_help
            ;;
        "")
            show_help
            ;;
        *)
            print_error "未知选项: $1"
            show_help
            exit 1
            ;;
    esac
}

# 捕获Ctrl+C信号
trap 'print_info "收到中断信号，正在停止服务..."; stop_services; exit 0' INT

# 运行主函数
main "$@" 